﻿using AutoMapper;
using B.S.Production.Domain.Entities;
using B.S.Production.ErrorCode;
using B.S.Production.Read.API.Application.Command.BomMainMaterialsRequiredCommand;
using B.S.Production.Read.API.Dto;
using MediatR;
using SqlSugar;

namespace B.S.Production.Read.API.Application.CommandHandler.BomMainMaterialsRequiredCommandHandler
{
    public class ShowBomMainMaterialsRequiredCommandHandler : IRequestHandler<ShowBomMainMaterialsRequiredCommand, ApiPaging<BomMainMaterialsRequiredDTO>>
    {
        private readonly ISqlSugarClient db;
        private readonly IMapper mapper;

        public ShowBomMainMaterialsRequiredCommandHandler(ISqlSugarClient db, IMapper mapper)
        {
            this.db = db;
            this.mapper = mapper;
        }

        public async Task<ApiPaging<BomMainMaterialsRequiredDTO>> Handle(ShowBomMainMaterialsRequiredCommand request, CancellationToken cancellationToken)
        {
            ApiPaging<BomMainMaterialsRequiredDTO> result = new ApiPaging<BomMainMaterialsRequiredDTO>();
            var list = db.Queryable<BomMainMaterialsRequired>();
            //总条数
            var totalCount = list.Count();
            //总页数
            var pageCount = (int)Math.Ceiling(totalCount * 1.0 / request.PageSize);
            //分页显示
            list = list.OrderByDescending(a => a.BomMainId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);
            result.TotalCount = totalCount;
            result.TotalPage = pageCount;
            result.Items = mapper.Map<List<BomMainMaterialsRequiredDTO>>(list.ToList());

            result.Code = ApiEnums.查询成功;
            result.Msg = ApiEnums.查询成功.ToString();


            return await Task.FromResult(result);
        }
    }
}
